import type { UserStoreType } from "@/typings/stores";
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { persist, devtools, createJSONStorage } from "zustand/middleware";

const initialState: UserStoreType.stateType = {
  token: "",
  userInfo: {},
  authButtonList: [], // 后端返回的字符权限数据
  authRoleList: [] // 后端返回的角色权限数据
};

const actions = (set: UserStoreType.settersStoreType) => {
  const setToken = (token: string) => {
    set((state: UserStoreType.stateType) => {
      state.token = token;
    });
  };

  const setUserInfo = (payload: Record<string, any>) => {
    set((state: UserStoreType.stateType) => {
      state.userInfo = payload.userInfo ?? {};
    });
  };

  const setAuthPermission = (payload: Record<string, any>) => {
    set((state: UserStoreType.stateType) => {
      state.authButtonList = payload.permissions ?? [];
    });
  };

  const setAuthRole = (payload: Record<string, any>) => {
    set((state: UserStoreType.stateType) => {
      state.authRoleList = payload.roles ?? [];
    });
  };

  const clearUserInfo = () => {
    set(useUserStore.getInitialState());
  };

  return { setToken, setUserInfo, setAuthPermission, setAuthRole, clearUserInfo };
};

const devtoolsConfig = { name: "REACT_APP_USER_STORAGE", enabled: import.meta.env.VITE_APP_REDUX_DEVTOOLS === "true" };
const persistConfig = { name: "REACT_APP_USER_STORAGE", storage: createJSONStorage(() => localStorage) };
export const useUserStore = create<UserStoreType.storeType>()(
  devtools(
    persist(
      immer((set) => ({
        ...initialState,
        ...actions(set)
      })),
      persistConfig
    ),
    devtoolsConfig
  )
);
